4
4
.
.
1
1
.
.
4
4
E
E
x
x
a
a
m
m
p
p
l
l
e
e
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows a basic example of JUnit 5 Test Method.
Tutorial isn't using @SpringBootTest which means that @Autowired isn't work which is why we use new MyController().
This approach is useful when we don't need Spring Boot Context so that tests could run faster.
Application Schema [Result]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
http://localhost:8080/Hello
Tomcat
hello()
MyController
MyControllerTest
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_junit (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
Create Test Class: MyControllerTest.java
MyController.java
package com.ivoronline.springboot_junit.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
return "Hello from Controller";
}
}
MyControllerTest.java
package com.ivoronline.springboot_junit.controllers;
import com.ivoronline.springboot_junit.controllers.MyController;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MyControllerTest {
@Test
void hello() {
//PERFORM ACTION
MyController myController = new MyController();
String result = myController.hello();
//TEST RESULT
assertEquals("Hello from Controller", result);
}
}
R
R
e
e
s
s
u
u
l
l
t
t
http://localhost:8080/Hello
Run Test Class: PersonTest
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>